package com.itheima.reggie.Controller;


import com.itheima.reggie.commom.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){

        String  originalFilename= file.getOriginalFilename();
        String suffix =  originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID() + suffix;
        log.info(fileName);
        try {
            file.transferTo(new File("D:\\img\\"+fileName));
        }catch (IOException e){
            e.printStackTrace();
        }
        return Result.success(fileName);
    }


    @GetMapping("/download")
    public void download(HttpServletResponse response,String name){
        //输入流

        //输出流
        try {
            FileInputStream fileInputStream = new FileInputStream(new File("D:\\img\\"+name));
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");
            byte[] bytes = new byte[1024];
            int len = 0;
            while((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            outputStream.close();
            fileInputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
